package top.hmtools.security;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class AESTools {

    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";


    /**
     *  AES加密
    * <br>方法说明：                    encryptData
    * <br>输入参数说明：           
    * <br>@param key
    * <br>@param data
    * <br>@return
    * <br>@throws Exception
    * <br>输出参数说明：
    * <br>byte[]           
     * @throws NoSuchPaddingException 
     * @throws NoSuchAlgorithmException 
     * @throws InvalidKeyException 
     * @throws BadPaddingException 
     * @throws IllegalBlockSizeException 
    *
     */
    public static byte[] encryptData(byte[] key,byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
        if(key == null || data == null){
            return null;
        }
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM);//SecretKeySpec类是KeySpec接口的实现类,用于构建秘密密钥规范
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // 创建密码器
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化
        return cipher.doFinal(data);
    }

    /**
     * AES解密
    * <br>方法说明：                    decryptData
    * <br>输入参数说明：           
    * <br>@param key
    * <br>@param data
    * <br>@return
    * <br>@throws NoSuchAlgorithmException
    * <br>@throws NoSuchPaddingException
    * <br>@throws InvalidKeyException
    * <br>@throws IllegalBlockSizeException
    * <br>@throws BadPaddingException
    * <br>输出参数说明：
    * <br>byte[]           
    *
     */
    public static byte[] decryptData(byte[] key,byte[] data)throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
        if(key == null || data == null){
            return null;
        }
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM);//SecretKeySpec类是KeySpec接口的实现类,用于构建秘密密钥规范
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return cipher.doFinal(data);
    }

}
